package com.ice.demo.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FunReference {
    public static void main(String[] args) {
        String[] array = new String[]{"apple", "Orange", "Banana", "Lemon"};
        Arrays.sort(array, FunReference::cmp2); // 静态方法引用
        Arrays.sort(array, String::compareTo); // 实例方法引用
        Arrays.sort(array, String::compareToIgnoreCase); // 实例方法引用
        System.out.println(String.join(", ", array));

        // 怎么可以
        //  List<String> names = List.of("Bob", "Alice", "Tim");
        //  List<Person> persons = ???

        // 1.传统做法
        List<String> names = List.of("Bob", "Alice", "Tim");
        List<Person> persons = new ArrayList<>();
        for (String name : names) {
            persons.add(new Person(name));
        }
        System.out.println("persons = " + persons);

        // 2.使用函数引用
        List<Person> persons2 = new ArrayList<>();
        names.forEach(name -> persons2.add(new Person(name)));
        System.out.println("persons2 = " + persons2);

        // 3.调用构造方法引用
        List<Person> persons3 = names.stream().map(Person::new).collect(Collectors.toList());
        persons3.add(new Person("Ice"));
        System.out.println("persons3 = " + persons3);


    }

    static int cmp(String s1, String s2) {
        return s1.compareTo(s2);
    }

    static int cmp2(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }




}


class Person {
    String name;
    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person:" + this.name;
    }
}